<template>
	<view class="login-container">
		<view class="login-header">
			<image class="header-bg" src="/static/images/login-bg.png" mode="aspectFill"></image>
			<view class="header-content">
				<image class="logo" src="/static/images/logo.png" mode="aspectFill"></image>
				<text class="app-name">定转子检测系统</text>
				<text class="slogan">专业高效的电机定转子检测解决方案</text>
			</view>
		</view>

		<view class="login-box">
			<view class="welcome-text">
				<text class="welcome">欢迎使用</text>
				<text class="desc">请授权微信登录以使用完整功能</text>
			</view>

			<button class="auth-btn" @click="handleAuthLogin">
				<u-icon name="weixin-fill" color="#ffffff" size="40"></u-icon>
				<text>微信一键登录</text>
			</button>
			
			<!-- 获取手机号按钮 -->
			<button v-if="isLoggedIn && !hasPhoneNumber" class="auth-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
				<u-icon name="phone-fill" color="#ffffff" size="40"></u-icon>
				<text>授权手机号</text>
			</button>

			<view class="agreement">
				<u-checkbox v-model="agreed" @change="onAgreementChange" shape="circle" activeColor="#07c160"></u-checkbox>
				<text class="agreement-text">我已阅读并同意<text class="link" @click="showAgreement">《用户协议》</text>和<text class="link" @click="showPrivacy">《隐私政策》</text></text>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/utils/api.js';
	import userManager from '@/utils/user.js';

	export default {
		data() {
			return {
				agreed: false,
				isLoggedIn: false,
				hasPhoneNumber: false,
				userInfo: null
			}
		},
		onLoad() {
			// 检查是否已登录
			this.checkLoginStatus();
		},
		methods: {
			onAgreementChange(value) {
				this.agreed = value;
				console.log('Agreement status:', value);
			},
			
			checkLoginStatus() {
				const isLoggedIn = userManager.isLoggedIn();
				this.isLoggedIn = isLoggedIn;
				
				if (isLoggedIn) {
					const userInfo = userManager.getUserInfo();
					this.userInfo = userInfo;
					this.hasPhoneNumber = userInfo && userInfo.phone;
					
					// 如果已登录且有手机号，跳转到首页
					if (this.hasPhoneNumber) {
						this.navigateToHome();
					}
				}
			},
			
			// 处理微信授权登录
			handleAuthLogin() {
				console.log('Current agreement status:', this.agreed);
				if (!this.agreed) {
					uni.showToast({
						title: '请先同意用户协议和隐私政策',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				
				uni.showLoading({
					title: '登录中...'
				});
				
				// 获取微信登录凭证和用户信息
				uni.getUserProfile({
					desc: '用于完善用户资料',
					success: (profileRes) => {
						const userInfo = profileRes.userInfo;
						
						// 获取登录凭证
						uni.login({
							provider: 'weixin',
							success: (loginRes) => {
								if (loginRes.code) {
									// 调用后端登录接口
									api.searchOpenid({
										code: loginRes.code,
										avatarUrl: userInfo.avatarUrl,
										nickName: userInfo.nickName
									}).then(res => {
										uni.hideLoading();
										
										if (res && res.token) {
											// 保存用户信息和登录状态
											const userData = {
												...res.user,
												token: res.token
											};
											
											userManager.saveUserInfo(userData);
											this.userInfo = userData;
											this.isLoggedIn = true;
											this.hasPhoneNumber = userData.phone ? true : false;
											
											// 如果已有手机号，直接跳转到首页
											if (this.hasPhoneNumber) {
												this.navigateToHome();
											} else {
												uni.showToast({
													title: '请授权手机号',
													icon: 'none'
												});
											}
										} else {
											uni.showToast({
												title: '登录失败，请重试',
												icon: 'none'
											});
										}
									}).catch(err => {
										uni.hideLoading();
										uni.showToast({
											title: '登录失败，请重试',
											icon: 'none'
										});
										console.error('登录失败', err);
									});
								} else {
									uni.hideLoading();
									uni.showToast({
										title: '登录失败，请重试',
										icon: 'none'
									});
								}
							},
							fail: (err) => {
								uni.hideLoading();
								uni.showToast({
									title: '登录失败，请重试',
									icon: 'none'
								});
								console.error('微信登录失败', err);
							}
						});
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: '获取用户信息失败',
							icon: 'none'
						});
						console.error('获取用户信息失败', err);
					}
				});
			},
			
			// 获取手机号
			getPhoneNumber(e) {
				if (e.detail.errMsg !== 'getPhoneNumber:ok') {
					uni.showToast({
						title: '获取手机号失败，请重试',
						icon: 'none'
					});
					return;
				}
				
				uni.showLoading({
					title: '处理中...'
				});
				
				// 调用后端接口获取手机号
				api.getWxPhoneNumber({
					phoneCode: e.detail.code
				}).then(res => {
					uni.hideLoading();
					
					if (res && res.phoneNumber) {
						// 更新用户信息
						const userInfo = userManager.getUserInfo();
						userInfo.phone = res.phoneNumber;
						userManager.saveUserInfo(userInfo);
						
						this.userInfo = userInfo;
						this.hasPhoneNumber = true;
						
						uni.showToast({
							title: '手机号授权成功',
							icon: 'success'
						});
						
						// 跳转到首页
						setTimeout(() => {
							this.navigateToHome();
						}, 1000);
					} else {
						uni.showToast({
							title: '获取手机号失败，请重试',
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					uni.showToast({
						title: '获取手机号失败，请重试',
						icon: 'none'
					});
					console.error('获取手机号失败', err);
				});
			},
			
			// 跳转到首页
			navigateToHome() {
				uni.reLaunch({
					url: '/pages/index/index'
				});
			},
			
			// 显示用户协议
			showAgreement() {
				// 跳转到用户协议页面
				uni.navigateTo({
					url: '/pages/agreement/user-agreement'
				});
			},
			
			// 显示隐私政策
			showPrivacy() {
				// 跳转到隐私政策页面
				uni.navigateTo({
					url: '/pages/agreement/privacy-policy'
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.login-container {
		height: 100vh;
		background-color: #ffffff;

		.login-header {
			position: relative;
			height: 400rpx;

			.header-bg {
				width: 100%;
				height: 100%;
			}

			.header-content {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				.logo {
					width: 120rpx;
					height: 120rpx;
					border-radius: 20rpx;
					margin-bottom: 20rpx;
				}

				.app-name {
					font-size: 40rpx;
					color: #ffffff;
					font-weight: bold;
					margin-bottom: 10rpx;
				}

				.slogan {
					font-size: 28rpx;
					color: rgba(255, 255, 255, 0.8);
				}
			}
		}

		.login-box {
			padding: 40rpx;

			.welcome-text {
				margin-bottom: 60rpx;

				.welcome {
					font-size: 36rpx;
					color: #303133;
					font-weight: bold;
					margin-bottom: 10rpx;
					display: block;
				}

				.desc {
					font-size: 28rpx;
					color: #909399;
				}
			}

			.auth-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				height: 90rpx;
				background-color: #07c160;
				border-radius: 45rpx;
				margin-bottom: 60rpx;

				text {
					font-size: 32rpx;
					color: #ffffff;
					margin-left: 10rpx;
				}
			}

			.user-info-box {
				margin-bottom: 30rpx;
				
				.avatar-btn {
					background: none;
					padding: 0;
					margin: 0;
					border: none;
					display: flex;
					flex-direction: column;
					align-items: center;
					
					&::after {
						border: none;
					}
					
					.avatar-preview {
						width: 160rpx;
						height: 160rpx;
						border-radius: 50%;
						margin-bottom: 20rpx;
					}
					
					text {
						font-size: 28rpx;
						color: #666666;
					}
				}
				
				.nickname-input {
					margin: 30rpx 0;
					
					.input {
						width: 100%;
						height: 80rpx;
						background-color: #f5f5f5;
						border-radius: 40rpx;
						padding: 0 30rpx;
						font-size: 28rpx;
					}
				}
				
				.confirm-btn {
					width: 100%;
					height: 90rpx;
					background-color: #07c160;
					border-radius: 45rpx;
					color: #ffffff;
					font-size: 32rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-top: 30rpx;
					
					&::after {
						border: none;
					}
				}
			}

			.agreement {
				display: flex;
				align-items: center;
				justify-content: center;

				.agreement-text {
					font-size: 24rpx;
					color: #909399;
					margin-left: 2rpx;

					.link {
						color: #306EF6;
					}
				}
			}
		}
	}
</style>